package com.onlinelearn.notifyservice.service;

import com.onlinelearn.notifyservice.dto.NotificationDTO;
import com.onlinelearn.notifyservice.model.Notification;
import com.onlinelearn.notifyservice.model.NotificationType;
import com.onlinelearn.notifyservice.model.NotificationStatus;
import com.onlinelearn.notifyservice.repository.NotificationRepository;
import com.onlinelearn.notifyservice.event.NotificationEventPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NotificationService {
    private final NotificationRepository notificationRepository;
    private final NotificationEventPublisher eventPublisher;
    private final EmailService emailService;
    private final SMSService smsService;

    @Autowired
    public NotificationService(
        NotificationRepository notificationRepository,
        NotificationEventPublisher eventPublisher,
        EmailService emailService,
        SMSService smsService
    ) {
        this.notificationRepository = notificationRepository;
        this.eventPublisher = eventPublisher;
        this.emailService = emailService;
        this.smsService = smsService;
    }

    @Transactional
    public NotificationDTO createNotification(NotificationDTO notificationDTO) {
        Notification notification = convertToEntity(notificationDTO);
        Notification savedNotification = notificationRepository.save(notification);
        
        // 发布通知事件
        eventPublisher.publishNotificationEvent(savedNotification);
        
        return convertToDTO(savedNotification);
    }

    @Transactional(readOnly = true)
    public List<NotificationDTO> getUnreadNotifications(Long userId) {
        List<Notification> unreadNotifications = notificationRepository.findByUserIdAndIsReadFalse(userId);
        return unreadNotifications.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Transactional
    public void markNotificationAsRead(Long notificationId) {
        Notification notification = notificationRepository.findById(notificationId)
            .orElseThrow(() -> new RuntimeException("Notification not found"));
        
        notification.setIsRead(true);
        notification.setStatus(NotificationStatus.READ);
        notificationRepository.save(notification);
    }

    @Transactional
    public void sendNotification(Long userId, NotificationType type, String content) {
        Notification notification = new Notification();
        notification.setUserId(userId);
        notification.setType(type);
        notification.setContent(content);
        notification.setTimestamp(LocalDateTime.now());
        notification.setIsRead(false);
        notification.setStatus(NotificationStatus.UNREAD);

        Notification savedNotification = notificationRepository.save(notification);

        // 根据通知类型发送
        switch (type) {
            case EMAIL:
                emailService.sendSimpleMessage(getUserEmail(userId), type.name(), content);
                break;
            case SMS:
                smsService.sendSMS(getUserPhoneNumber(userId), content);
                break;
        }
    }

    public void processLocalNotification(Notification notification) {
        // 本地通知处理逻辑
        // 可以添加额外的本地处理，如日志记录等
    }

    private Notification convertToEntity(NotificationDTO dto) {
        Notification notification = new Notification();
        notification.setUserId(dto.getUserId());
        notification.setType(dto.getType());
        notification.setContent(dto.getContent());
        notification.setTimestamp(LocalDateTime.now());
        notification.setIsRead(false);
        notification.setStatus(NotificationStatus.UNREAD);
        return notification;
    }

    private NotificationDTO convertToDTO(Notification notification) {
        NotificationDTO dto = new NotificationDTO();
        dto.setId(notification.getId());
        dto.setUserId(notification.getUserId());
        dto.setType(notification.getType());
        dto.setContent(notification.getContent());
        dto.setTimestamp(notification.getTimestamp());
        dto.setIsRead(notification.getIsRead());
        return dto;
    }

    private String getUserEmail(Long userId) {
        // 从用户服务获取用户邮箱
        return "user@example.com";
    }

    private String getUserPhoneNumber(Long userId) {
        // 从用户服务获取用户手机号
        return "13800138000";
    }
} 
} 